package com.csc775;

import java.io.IOException;
import java.io.OptionalDataException;

import com.csc775.gui.LoginActivity;
import com.csc775.gui.TalkActivity;
import com.csc775.message.ControlMessage;
import com.csc775.message.ControlRquestType;
import com.csc775.networking.Client;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
/**
 * This class is the main starting activity that will be up
 * when application is up.
 * @author pkulkar
 *
 */
public class AndroidWalkieTalkieActivity extends Activity {
	

    /** Called when the activity is first created. */
	Button btnRegister = null;
	Button btnLogin = null;
	private boolean connected = false;
	private static Client client=null;
	public static final String serverIP = "192.168.0.197";
	public static final int serverPort = 2005;
	public static String currentUserName=null;
	EditText username;
	EditText password;
	public static boolean isLonin = false;
	
	/**
	 * This will return the client object create 
	 * if the user is logged in
	 * @return
	 */
	public static Client getClient(){
		return client;
	}
	/**
	 * This will method will create the activity
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        // Register button click
        btnRegister= (Button) findViewById(R.id.LoginRegisterButton);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
			public void onClick(View view) {
            	isLonin = false;
                Intent myIntent = new Intent(view.getContext(), LoginActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });
        // login button click
        btnLogin= (Button) findViewById(R.id.signInButton);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
			public void onClick(View view) {
            	// this flag helps to unederstand which path just came reached till
            	// TalkActivity. Regierting or by login
            	isLonin = true;
            	username = (EditText) findViewById(R.id.txtUserName);
        		password = (EditText) findViewById(R.id.txtPassword);

        		if(username.getText().toString().isEmpty()
						|| password.getText().toString().isEmpty()){
					
					Toast toast = Toast.makeText(getApplicationContext(), "Please enter user credential.", Toast.LENGTH_LONG);
					toast.show();
					return;
				}
				StringBuffer buf = new StringBuffer();
				buf.append(username.getText().toString());
				buf.append("~");
				buf.append(password.getText().toString());

				ControlMessage msg = new ControlMessage(serverIP, serverPort,
						buf.toString().length(), buf.toString());
				msg.setRequestType(ControlRquestType.LOGIN);// request login by setting type
				Log.v("EditText", msg.toString());
				
				// this create a new client object. This is a networking layer implementation 
				// at android phone side.
				client=new Client();
				 // this will store output and input stream information of TCP connection for client
				 if (client.run()) {
					 client.Sendmessage(msg.toString());
					 {
						 try {
							String str =(String) client.getOis().readObject();// wait on output stream of TCP connection with server
							// parse message came from client
							ControlMessage msgObj = ControlMessage.getControlMessageInstance(str);
							int type = msgObj.getRequestType();
							
							switch(type){
								// based on acks received from server, take an action
								case ControlRquestType.LOGIN_ACK :
									// successfull sign in 
									if(msgObj.getExtraData().equals("SUCCESS")){
										// save current user name
										currentUserName=username.getText().toString();
										Toast toast = Toast.makeText(getApplicationContext(), "Welcome "+currentUserName, Toast.LENGTH_LONG);
										toast.show();
										msg = new ControlMessage(serverIP, serverPort,
												buf.toString().length(), buf.toString());
										msg.setRequestType(100);
										finish();
										// switch to talk activity as login success
						                Intent myIntent = new Intent(view.getContext(), TalkActivity.class);
						                startActivityForResult(myIntent, 0);
									}else if(msgObj.getExtraData().equals("NOT_VALID_PASSWORD")){
										Toast toast = Toast.makeText(getApplicationContext(), "Invalid password", Toast.LENGTH_LONG);
										toast.show();
									}else if(msgObj.getExtraData().equals("INVALID_USER")){
										Toast toast = Toast.makeText(getApplicationContext(), "User does not exist\nPlease register.", Toast.LENGTH_LONG);
										toast.show();
									}
									break;
							default:
							}
						} catch (OptionalDataException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					 }
		            }else{
		            	Toast toast = Toast.makeText(getApplicationContext(), "Service discovery server in down!",Toast.LENGTH_LONG);
						toast.show();
		            }
            }

        });
    }
}